package com.shareyi.jshop.autocode;

import com.shareyi.joywindow.JoyWindowData;
import com.shareyi.joywindow.JoyWindowIE;
import com.shareyi.joywindow.JoyWindowIntf;
import com.shareyi.joywindow.enumtype.ServerStartType;
import com.shareyi.joywindow.sys.utils.BindResource;
import com.shareyi.joywindow.window.JoyWindowSwing;
import com.shareyi.simpleserver.core.SimpleHttpServer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.Properties;


public class StartWindow {

	private static Log log = LogFactory.getLog(StartWindow.class);

	public static void main(String[] args) {

		//是否只启动了server
		ServerStartType serverStartType=ServerStartType.SERVER_WINDOW;
		Properties serverInfo=BindResource.getProperties("config/server");
		if(serverInfo!=null){
			String startType=serverInfo.getProperty("serverStartType");
			serverStartType=ServerStartType.getByType(startType);
			if(serverStartType==null){
				serverStartType=ServerStartType.SERVER_WINDOW;
			}
		}

		JoyWindowIntf intf=null;
		if(serverStartType==ServerStartType.SERVER_WINDOW){
			intf=JoyWindowIE.getJoyWindow();
			try {
				intf.init();		//初始化
				log.info("读取配置文件，同时启动server 和 window");
			}catch (Exception e) {
				log.error("启动SWT窗口失败",e);
				System.exit(0);
			}
		}else if(ServerStartType.SERVER_SWING==serverStartType){
			intf= JoyWindowSwing.getInstance();
			try {
				intf.init();		//初始化
				log.info("读取配置文件，同时启动server 和 swing");
			}catch (Exception e) {
				log.error("启动Swing窗口失败",e);
				System.exit(0);
			}
		}else{
			log.info("读取配置文件，只启动server");
		}

		
		try{
			SimpleHttpServer.getServerInstance().startServer();			//启动服务器
		}catch(Exception e) {
			log.error("启动服务器失败", e);
			if(intf!=null){
				intf.alertMsg(e.getMessage());
			}
			System.exit(0);
		}
			
		JoyWindowData.setJoyWindow(intf);
		JoyWindowData.setHttpServer(SimpleHttpServer.getServerInstance());
		log.info("服务器已经启动，监听端口：" + SimpleHttpServer.getServerInstance().getPort());

		if(intf!=null){
			try {
				intf.openWindow();	//显示界面

				if(ServerStartType.SERVER_SWING==serverStartType){
					StringBuilder stringBuilder=new StringBuilder();
					String httpUrl="http://127.0.0.1:"+SimpleHttpServer.getServerInstance().getPort()+"/";
					stringBuilder.append("<html><h1>说明</h1> 本窗口仅仅提供文件选择器功能，体验较差，请使用windows版本的！");
					stringBuilder.append("<p>服务已经启动，请用浏览器打开地址访问：</p>");
					stringBuilder.append("<a href=\"");
					stringBuilder.append(httpUrl).append("\">");
					stringBuilder.append(httpUrl).append("</a>");
					stringBuilder.append("</html>");
					intf.setText(stringBuilder.toString());
				}

				log.info("服务器已经启动，窗口已经打开！");
			} catch (Exception e) {
				intf.alertMsg("界面初始化失败");
				System.exit(0);
			}
		}




	}
}
